import {FlashList, FlashListProps} from '@shopify/flash-list';
import {View, ActivityIndicator} from 'react-native';
import {Text} from 'tsun-smart-ui';
import EmptyContent from '@/components/EmptyContent';
import {useTranslation} from 'react-i18next';
import usePage from '@/hooks/usePage';
import {useSlot, SlotChildren, Slot, createTemplate} from '@beqa/react-slots';
import {type ApiResponse} from '@/services/http';
type Api = (
  params: any,
) => Promise<ApiResponse<{records: any[]; total: number}>>;
export const PageTemplate = createTemplate<ChildrenProps<Api>>();
type ChildrenProps<T> = SlotChildren<Slot<ReturnType<typeof usePage<T>>>>;
const PageContent = <R,>({
  renderItem,
  api,
  params,
  children,
}: Omit<FlashListProps<R>, 'data'> & {
  api: Api;
  params?: any;
  children?: ChildrenProps<R>;
}) => {
  const {t} = useTranslation();
  const {slot} = useSlot(children);
  const {loading, list, pageInfo, dispatch, hasMore, ...rest} = usePage<R>(
    api,
    params,
  );  
  return (
    <>
      <slot.default
        loading={loading}
        list={list}
        pageInfo={pageInfo}
        dispatch={dispatch}
        hasMore={hasMore}
        {...rest}></slot.default>
      <FlashList
        renderItem={renderItem}
        data={list}
        showsVerticalScrollIndicator={false}
        ListEmptyComponent={
          <EmptyContent title={t('workplace.record.nodata')} />
        }
        ItemSeparatorComponent={() => <View className="h-3" />}
        ListFooterComponent={
          <View className=" justify-center items-center mt-3 mb-4">
            {loading ? (
              <ActivityIndicator />
            ) : (
              !hasMore &&
              list.length > 0 && (
                <Text>{t('message. alreadyReachBottom')}~~~</Text>
              )
            )}
          </View>
        }
        onEndReachedThreshold={0.1}
        onEndReached={() => {
          if (!loading && hasMore) {
            dispatch({
              type: 'setPageNum',
              payload: pageInfo.pageNum + 1,
            });
          }
        }}></FlashList>
    </>
  );
};
export default PageContent;
